package com.budwk.app.sqfw.services.impl.SecurityInvestigationImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.AirSourceUsageEnum;
import com.budwk.app.sqfw.enums.SafeHazardA13Enum;
import com.budwk.app.sqfw.enums.SqfwFormSummaryFieldEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.services.SecurityInvestigationService;
import com.budwk.app.sqfw.services.SqfwFormSummaryService;
import com.budwk.app.sqfw.services.impl.SqfwSummaryForAdminServiceImpl;
import com.budwk.app.sqfw.vo.Sqfw_formSummaryForAdminVO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.CommonFormOfficeForAdminUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@IocBean(name = "jinYangStreetService")
@Slf4j
public class JinYangStreeServiceImpl implements SecurityInvestigationService {

    @Inject
    private SqfwFormSummaryService sqfwFormSummaryService;
    @Inject
    private CommunityStreetComponent communityStreetComponent;
    @Inject
    private SysUserService sysUserService;

    private static final String GUIZHOUS = "贵州省";

    private static final String CITY = "贵阳市";

    private static final String QUXIAN = "观山湖区";

    private static final String ZHISHU = "直属";

    private static final String STREET = "金阳街道";

    @Override
    public Criteria buildQueryCond(Sqfw_formSummaryForAdminVO forAdminVo) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        criSql.andEquals(Sqfw_formSummaryForAdminVO::getType, SqfwFormSummaryConstants.safety_check)
                .andEquals(Sqfw_formSummaryForAdminVO::getCity, CITY)
                .andEquals(Sqfw_formSummaryForAdminVO::getDistrict, QUXIAN)
                .andEquals(Sqfw_formSummaryForAdminVO::getCounty, STREET);
        // 组装查询条件
        if (Strings.isNotBlank(forAdminVo.getPageOrderName()) && Strings.isNotBlank(forAdminVo.getPageOrderBy())) {
            if (forAdminVo.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(forAdminVo.getPageOrderName());
            }
            if (forAdminVo.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(forAdminVo.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary::getFillDate);
        }
        // 辖区
        if (Strings.isNotBlank(forAdminVo.getCommunity())) {
            criSql.andLike(Sqfw_formSummary::getCommunity, forAdminVo.getCommunity());
        }
        // 时间
        communityStreetComponent.handleQueryTime(forAdminVo, criSql);
        // 场所名称 a1
        if (StringUtils.isNotEmpty(forAdminVo.getA1())) {
            SqlExpressionGroup a1 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA1, "like", "%" + forAdminVo.getA1() + "%");
            SqlExpressionGroup a4 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA4, "like", "%" + forAdminVo.getA4() + "%");
            criSql.and(a1.or(a4));
        }
        // 经营地址 a3
        if (StringUtils.isNotEmpty(forAdminVo.getA3())) {
            criSql.andLike(Sqfw_formSummary::getA3, forAdminVo.getA3());
        }
        // 安全隐患整改状态 a15 全部的话不传递
        if (StringUtils.isNotEmpty(forAdminVo.getA13())) {
            if (!forAdminVo.getA13().equals(SafeHazardA13Enum.ALL.getName())) {
                criSql.andEquals(Sqfw_formSummary::getA13, forAdminVo.getA13());
            }
        }
        // 气源使用情况
        if (StringUtils.isNotEmpty(forAdminVo.getA21())) {
            if (!forAdminVo.getA21().equals(AirSourceUsageEnum.ALL.getName())) {
                String[] a21s = forAdminVo.getA21().split(",");
                StringBuilder sb = new StringBuilder();
                for (String a21 : a21s) {
                    String code = AirSourceUsageEnum.getCode(a21);
                    if (StringUtils.isNotBlank(code)) {
                        sb.append(code).append(",");
                    }
                }
                if (sb.length() > 0) {
                    String substring = sb.substring(0, sb.length() - 1);
                    criSql.andLike(Sqfw_formSummary::getA21, substring);
                }
            }
        }
        //  负责人 a2
        if (StringUtils.isNotEmpty(forAdminVo.getA2())) {
            criSql.andLike(Sqfw_formSummary::getA2, forAdminVo.getA2());
        }
        // 检查人员 createUserName
        if (StringUtils.isNotEmpty(forAdminVo.getCreateUserName())) {
            criSql.andLike(Sqfw_formSummary::getCreateUserName, forAdminVo.getCreateUserName());
        }

        // 数据统计页面 隐患数据跳转过来查询列表使用 add by LJT 2023-11-16
        if(Strings.isNotBlank(forAdminVo.getIssueStatus()) && "statistic".equals(forAdminVo.getIssueStatus())) {
            criSql.andNotEquals(Sqfw_formSummary::getIssueStatus,null);
            criSql.andNotEquals(Sqfw_formSummary::getIssueStatus,"正常");
        }

        // 非数据统计页面 是否存在隐患 add by LJT 2023-12-07
        if(Strings.isNotBlank(forAdminVo.getIssueStatus()) && !"statistic".equals(forAdminVo.getIssueStatus())) {
            if ("是".equals(forAdminVo.getIssueStatus())) {
                criSql.andNotEquals(Sqfw_formSummary::getIssueStatus,null);
                criSql.andNotEquals(Sqfw_formSummary::getIssueStatus,"正常");
            } else if ("否".equals(forAdminVo.getIssueStatus())) {
                criSql.andEquals(Sqfw_formSummary::getIssueStatus, "正常");
            }
        }

        if (Strings.isNotBlank(forAdminVo.getQueryAll())) {
            String queryAll = forAdminVo.getQueryAll();
            SqlExpressionGroup a1 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA1, "like", "%" + queryAll + "%");
            SqlExpressionGroup a4 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA4, "like", "%" + queryAll + "%");
            SqlExpressionGroup a2 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA2, "like", "%" + queryAll + "%");
            SqlExpressionGroup a3 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA3, "like", "%" + queryAll + "%");
            SqlExpressionGroup a15 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA15, "like", "%" + queryAll + "%");
            SqlExpressionGroup a21 = Cnd.exps(Sqfw_formSummaryForAdminVO::getA21, "like", "%" + queryAll + "%");
            SqlExpressionGroup district = Cnd.exps(Sqfw_formSummaryForAdminVO::getDistrict, "like", "%" + queryAll + "%");
            SqlExpressionGroup community = Cnd.exps(Sqfw_formSummaryForAdminVO::getCommunity, "like", "%" + queryAll + "%");
            SqlExpressionGroup createUserName = Cnd.exps(Sqfw_formSummaryForAdminVO::getCreateUserName, "like", "%" + queryAll + "%");
            criSql.and(a1.or(a2).or(a3).or(a4).or(a15).or(a21).or(district).or(community).or(createUserName));
        }
        criSql.andNotEquals(Sqfw_formSummary::getFillDate, CommonConstants.WASTE_CREATE_TIME);
        // 如果是查询未超时数据，只查询7天前的数据（需求）
        if (Strings.isNotBlank(forAdminVo.getCheckStatus()) && SqfwSummaryForAdminServiceImpl.TO_DO_CHECK_OUT.equals(forAdminVo.getCheckStatus())) {
            criSql.andEquals(Sqfw_formSummary::getCheckStatus, forAdminVo.getCheckStatus());
            Date offsetDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(DateUtil.offsetDay(new Date(), -CommonFormOfficeForAdminUtils.TIME_OUT)));
            criSql.and(Sqfw_formSummary::getFillDate, "<", offsetDate);
            criSql.and("check_status","!=", SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode());
        }
        // 需求：增加是否超时检查情况 add by LJT 2024-01-16
        if (Strings.isNotBlank(forAdminVo.getCheckStatus()) && SqfwSummaryForAdminServiceImpl.CHECK_OUT.equals(forAdminVo.getCheckStatus())) {
            Date offsetDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(DateUtil.offsetDay(new Date(), -CommonFormOfficeForAdminUtils.TIME_OUT)));
            SqlExpressionGroup e1 = Cnd.exps("fill_date", ">=", offsetDate);
            SqlExpressionGroup e2 = Cnd.exps("check_status", "!=", SqfwSummaryForAdminServiceImpl.TO_DO_CHECK_OUT);
            criSql.and(e1.or(e2));
            criSql.and("check_status","!=", SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode());
        }
        if (Strings.isNotBlank(forAdminVo.getCheckStatus()) && SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode().equals(forAdminVo.getCheckStatus())) {
            criSql.and("check_status", "=", forAdminVo.getCheckStatus());
        }
        return cri;
    }

    @Override
    public Result<Pagination> listSummaryByPage(Sqfw_formSummaryForAdminVO forAdminVo) {
        // 构建查询条件
        Criteria cnd = buildQueryCond(forAdminVo);
        Pagination pagination = sqfwFormSummaryService.listPage(forAdminVo.getPageNo(), forAdminVo.getPageSize(), cnd);
        if (pagination.getTotalCount() > 0) {
            // 空值处理
            List<Sqfw_formSummary> results = new ArrayList<>(50);
            for (Sqfw_formSummary formSummary : pagination.getList(Sqfw_formSummary.class)) {
                formSummary.setA21(AirSourceUsageEnum.handleCodesToName(formSummary.getA21()));
                results.add(StrUtil.formatSummaryNullStr(formSummary));
            }
            pagination.setList(results);
        }
        // 7天以内的数据状态改成2-已检查，前台方便展示
        if (Strings.isBlank(forAdminVo.getCheckStatus()) || SqfwSummaryForAdminServiceImpl.CHECK_OUT.equals(forAdminVo.getCheckStatus())) {
            List<Sqfw_formSummary> sqfwFormSummaryList = pagination.getList(Sqfw_formSummary.class);
            List<Sqfw_formSummaryForAdminVO> sqfwFormSummaryForAdminVOList = new ArrayList<Sqfw_formSummaryForAdminVO>();
            for (Sqfw_formSummary sqfwFormSummary : sqfwFormSummaryList) {
                Sqfw_formSummaryForAdminVO sqfwFormSummaryForAdminVO = new Sqfw_formSummaryForAdminVO();
                BeanUtil.copyProperties(sqfwFormSummary, sqfwFormSummaryForAdminVO);
                if (Strings.isNotBlank(sqfwFormSummary.getCheckStatus())
                        && SqfwSummaryForAdminServiceImpl.TO_DO_CHECK_OUT.equals(sqfwFormSummary.getCheckStatus().trim())
                        && null != sqfwFormSummaryForAdminVO.getFillDate()) {
                    Date offsetDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(DateUtil.offsetDay(new Date(), -CommonFormOfficeForAdminUtils.TIME_OUT)));
                    Date thisFillDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(sqfwFormSummaryForAdminVO.getFillDate()));
                    if (offsetDate.compareTo(thisFillDate) < 0) {
                        sqfwFormSummaryForAdminVO.setCheckStatus(SqfwSummaryForAdminServiceImpl.CHECK_OUT);
                    }
                }
                sqfwFormSummaryForAdminVOList.add(sqfwFormSummaryForAdminVO);
            }
            pagination.setList(sqfwFormSummaryForAdminVOList);
        }
        return Result.success(pagination);
    }

    @Override
    public boolean checkCurrentUserAuthority() {
        Sys_user user = sysUserService.fetch(SecurityUtil.getUserId());
        if (user == null) {
            throw new AppException(ResultCode.USER_NOT_FOUND.getMsg());
        }
        // 检查用户是否具有操作权限
        String province = user.getProvince();
        String city = user.getCity();
        String district = user.getDistrict();
        String county = user.getCounty();
        String community = user.getCommunity();

        // ○如果【province=贵州省】且【city=贵阳市】且【district=观山湖区】且【county=金阳街道】且【community=直属】时，可以看见数据统计页面。
        if (GUIZHOUS.equals(province) && CITY.equals(city) && QUXIAN.equals(district) && STREET.equals(county) && ZHISHU.equals(community)) {
            return true;
        }
        //○如果【province=贵州省】且【city=贵阳市】且【district=观山湖区】且【county=直属】时，可以看见数据统计页面。
        if (GUIZHOUS.equals(province) && CITY.equals(city) && QUXIAN.equals(district) && ZHISHU.equals(county)) {
            return true;
        }
        //○如果【province=贵州省】且【city=贵阳市】且【district=直属】时，可以看见数据统计页面。
        if (GUIZHOUS.equals(province) && CITY.equals(city) && ZHISHU.equals(district)) {
            return true;
        }
        //○如果【province=贵州省】且【city=直属】时，可以看见数据统计页面。
        if (GUIZHOUS.equals(province) && ZHISHU.equals(city)) {
            return true;
        }
        //○如果【province=直属】时，可以看见数据统计页面。
        if (ZHISHU.equals(province)) {
            return true;
        }
        throw new AppException("无权限操作！");
    }

    @Override
    public String generateServiceRecordPdfCollZipForBM(Sqfw_formSummaryForAdminVO forAdminVo) {
        // 1 构建查询条件
        Criteria cnd = buildQueryCond(forAdminVo);
        // 按照条件导出PDF
        String pdfUrl = communityStreetComponent.generateServiceRecordPdfCollZipForBM(cnd);
        CommonComponent.insertDownRecordLog(JSONObject.toJSONString(forAdminVo), JSONObject.toJSONString(Result.data(pdfUrl)), "金阳街道：按照查询条件导出PDF文件", pdfUrl, null);
        return pdfUrl;
    }

    @Override
    public String generateServiceRecordExcelCollZipForBM(Sqfw_formSummaryForAdminVO bean) {
        Criteria cnd = buildQueryCond(bean);
        // 按照条件导出
        String url = communityStreetComponent.generateServiceRecordExcelCollZipForBM(bean, cnd);
        CommonComponent.insertDownRecordLog(JSONObject.toJSONString(bean), JSONObject.toJSONString(Result.data(url)), "金阳街道：按照查询条件导出Excel文件", url, null);
        return url;
    }
}
